package com.jd.lme.example.patterns.interpretpattern;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class AndExpression implements Expression{
    private final List<Expression> expressions = new ArrayList<>();

    public AndExpression(String strAndExpression) {
        String[] strExpressions = strAndExpression.trim().split("&&");
        for (String strExpr : strExpressions) {
            if (strExpr.contains(">")) {
                expressions.add(new GreaterExpression(strExpr));
            } else if (strExpr.contains("<")) {
                expressions.add(new LessExpression(strExpr));
            } else if (strExpr.contains("==")) {
                expressions.add(new EqualExpression(strExpr));
            } else {
                throw new RuntimeException("Expression is invalid: " + strAndExpression);
            }
        }

    }

    @Override
    public boolean interpret(Map<String, Long> stats) {
        for (Expression expression : this.expressions) {
            if (!expression.interpret(stats)) {
                // 一但有一个失败则立即失败
                return false;
            }
        }
        return true;
    }
}
